package org.example.test.service.impl;

import cn.hutool.db.sql.Order;
import org.example.test.dal.entity.*;
import org.example.test.dal.mapper.*;
import org.example.test.model.OrderItemModel;
import org.example.test.model.OrdersModel;
import org.example.test.service.OrdersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class OrdersServiceImpl implements OrdersService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrdersServiceImpl.class);

    @Autowired
    private OrdersMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public OrdersModel createOrder(OrdersModel orderRequest) {
        try {
            User user = userMapper.selectByUserName(orderRequest.getUserName());
            Orders order = new Orders();
            order.setStatus(orderRequest.getStatus());
            order.setTotalPrice(orderRequest.getTotalPrice());
            order.setUserId(user.getId());
            orderMapper.insert(order);

            Long orderId = order.getId(); // 获取数据库生成的订单ID
            if (orderRequest.getOrderItems() != null && !orderRequest.getOrderItems().isEmpty()) {
                for (OrderItemModel item : orderRequest.getOrderItems()) {
                    OrderItem orderItem = new OrderItem();
                    orderItem.setOrderId(orderId);
                    orderItem.setImagePath(item.getImagePath());
                    orderItem.setProductId(item.getProductId());
                    orderItem.setQuantity(item.getQuantity());
                    orderItem.setPrice(item.getPrice());
                    orderItemMapper.insert(orderItem);
                }
            }
            return orderRequest;
        } catch (Exception e) {
            LOGGER.error("Error creating order", e);
            throw new RuntimeException("Error creating order: " + e.getMessage());
        }
    }

    @Override
    public void updateOrder(Long orderId, OrdersModel orderRequest) {
        try {
            Orders existingOrder = orderMapper.selectById(orderId);
            if (existingOrder == null) {
                throw new RuntimeException("Order not found");
            }

            orderRequest.setId(orderId);
            orderMapper.updateOrder(orderRequest);

            if (orderRequest.getOrderItems() != null) {
                for (OrderItemModel item : orderRequest.getOrderItems()) {
                    OrderItem existingItem = orderItemMapper.selectByOrderIdAndProductId(orderId, item.getProductId());
                    if (existingItem != null) {
                        existingItem.setQuantity(item.getQuantity());
                        existingItem.setPrice(item.getPrice());
                        orderItemMapper.updateAll(existingItem);
                    } else {
                        OrderItem orderItem = new OrderItem();
                        orderItem.setOrderId(orderId);
                        orderItem.setProductId(item.getProductId());
                        orderItem.setQuantity(item.getQuantity());
                        orderItem.setPrice(item.getPrice());
                        orderItemMapper.insert(orderItem);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("Error updating order", e);
            throw new RuntimeException("Error updating order: " + e.getMessage());
        }
    }

    @Override
    public void updateOrderStatus(Long orderId, String status) {
        orderMapper.updateStatus(orderId,status);
    }

    @Override
    public void deleteOrder(Long orderId) {
        try {
            orderItemMapper.deleteByOrderId(orderId);
            orderMapper.deleteOrder(orderId);
        } catch (Exception e) {
            LOGGER.error("Error deleting order", e);
            throw new RuntimeException("Error deleting order: " + e.getMessage());
        }
    }

    @Override
    public OrdersModel getOrderById(Long orderId) {
        try {
            Orders order = orderMapper.selectById(orderId);
            if (order == null) {
                throw new RuntimeException("Order not found");
            }

            OrdersModel orderModel = new OrdersModel();
            orderModel.setId(order.getId());
            orderModel.setStatus(order.getStatus());
            orderModel.setTotalPrice(order.getTotalPrice());
            orderModel.setUserName(order.getUserId());

            List<OrderItem> orderItems = orderItemMapper.selectByOrderId(orderId);
            List<OrderItemModel> orderItemModels = new ArrayList<>();
            for (OrderItem orderItem : orderItems) {
                OrderItemModel orderItemModel = new OrderItemModel();
                orderItemModel.setId(orderItem.getId());
                orderItemModel.setOrderId(orderItem.getOrderId());
                orderItemModel.setProductId(orderItem.getProductId());
                orderItemModel.setQuantity(orderItem.getQuantity());
                orderItemModel.setPrice(orderItem.getPrice());
                orderItemModels.add(orderItemModel);
            }
            orderModel.setOrderItems(orderItemModels);
            return orderModel;
        } catch (Exception e) {
            LOGGER.error("Error getting order", e);
            throw new RuntimeException("Error getting order: " + e.getMessage());
        }
    }

    @Override
    public List<OrdersModel> listOrdersByUser(Long userId) {
        try {
            // 1. 查询用户信息
            User user = userMapper.selectByUserName(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            // 2. 查询用户的所有订单
            List<Orders> orders = orderMapper.selectByUserId(user.getId());

            // 3. 遍历每个订单，查询对应的商品信息
            List<OrdersModel> ordersModels = new ArrayList<>();
            for (Orders order : orders) {
                // 查询订单的商品信息
                List<OrderItem> orderItems = orderItemMapper.selectByOrderId(order.getId());

                // 将 Orders 转换为 OrdersModel
                OrdersModel ordersModel = new OrdersModel();
                ordersModel.setId(order.getId());
                ordersModel.setUserName(order.getUserId());
                ordersModel.setTotalPrice(order.getTotalPrice());
                ordersModel.setStatus(order.getStatus());

                // 将 OrderItem 转换为 OrderItemModel
                List<OrderItemModel> orderItemModels = orderItems.stream()
                        .map(item -> {
                            OrderItemModel orderItemModel = new OrderItemModel();
                            orderItemModel.setId(item.getId());
                            orderItemModel.setOrderId(item.getOrderId());
                            orderItemModel.setProductId(item.getProductId());
                            orderItemModel.setPrice(item.getPrice());
                            orderItemModel.setQuantity(item.getQuantity());
                            orderItemModel.setImagePath(item.getImagePath());
                            return orderItemModel;
                        })
                        .collect(Collectors.toList());

                ordersModel.setOrderItems(orderItemModels);
                ordersModels.add(ordersModel);
            }

            return ordersModels;
        } catch (Exception e) {
            LOGGER.error("Error listing orders", e);
            throw new RuntimeException("Error listing orders: " + e.getMessage());
        }
    }

    @Override
    public OrdersModel checkoutCart(Long userId, List<Long> selectedProductIds,Double totalPrice) {
        try {
            // 获取用户的购物车
            Cart cart = cartMapper.selectByUserId(userId);
            if (cart == null) {
                throw new RuntimeException("Cart not found");
            }

            // 获取购物车商品
            List<CartItem> cartItems = cartItemMapper.selectByCartId(cart.getId());
            if (cartItems.isEmpty()) {
                throw new RuntimeException("Cart is empty");
            }

            // 过滤选中的商品
            List<CartItem> selectedItems = cartItems.stream()
                    .filter(item -> selectedProductIds.contains(item.getProductId()))
                    .collect(Collectors.toList());

            if (selectedItems.isEmpty()) {
                throw new RuntimeException("No selected items for checkout");
            }

            // 创建订单
            Orders order = new Orders();
            order.setStatus("PENDING"); // 初始状态
            order.setTotalPrice(BigDecimal.valueOf(totalPrice));
            order.setUserId(userId);
            orderMapper.insert(order);

            Long orderId = order.getId();

            for (CartItem cartItem : selectedItems) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(orderId);
                orderItem.setProductId(cartItem.getProductId());
                orderItem.setQuantity(cartItem.getQuantity());
                orderItem.setPrice(getProductPrice(cartItem.getProductId())); // 假设有获取商品价格的方法
                orderItemMapper.insert(orderItem);
            }

            // 清除购物车中已结算的商品
            cartItemMapper.deleteByCartIdAndProductIds(cart.getId(), selectedProductIds);

            // 返回订单信息
            OrdersModel orderModel = getOrderById(orderId);
            return orderModel;
        } catch (Exception e) {
            LOGGER.error("Error during checkout", e);
            throw new RuntimeException("Error during checkout: " + e.getMessage());
        }
    }

    @Override
    public List<OrderItemModel> getMerchantOrder(Long productId) {

        List<OrderItem> orderItems = orderItemMapper.selectByProductId(productId);
        List<OrderItemModel> orderItemModels = new ArrayList<>();
        for (OrderItem orderItem : orderItems) {
            OrderItemModel orderItemModel = new OrderItemModel();
            orderItemModel.setId(orderItem.getId());
            orderItemModel.setOrderId(orderItem.getOrderId());
            orderItemModel.setProductId(orderItem.getProductId());
            orderItemModel.setImagePath(orderItem.getImagePath());
            orderItemModel.setQuantity(orderItem.getQuantity());
            orderItemModel.setPrice(BigDecimal.valueOf(orderItem.getProductId()));

            Orders order = orderMapper.selectByPrimaryKey(orderItem.getOrderId());
            orderItemModel.setStatus(order.getStatus());
            User user = userMapper.selectByPrimaryKey(order.getUserId());
            orderItemModel.setAddress(user.getAddress());
            orderItemModels.add(orderItemModel);
        }
        return orderItemModels;
    }

    // 假设这里有一个方法可以获取商品价格
    private BigDecimal getProductPrice(Long productId) {
        ProductServiceImpl productServiceImpl = new ProductServiceImpl();
        List<Product> productList = productServiceImpl.searchProducts(String.valueOf(productId));

        // 这里需要从数据库或者其他微服务查询价格
        return productList.get(0).getPrice(); // 假设每个商品 100 元
    }

}
